package biz

import (
	"context"
	"customer/api/verifyCode"
	"github.com/go-kratos/kratos/contrib/registry/consul/v2"
	"github.com/go-kratos/kratos/v2/errors"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	"github.com/hashicorp/consul/api"
	"regexp"
	"time"
)

func Verification(pattern string, Telephone string) error {
	// 将正则表达式编译成一个正则对象（使用 PERL 语法）。
	// 该正则对象会采用“leftmost-first”模式。选择第一个匹配结果。
	// 如果正则表达式语法错误，则返回错误信息。
	regexpattern := regexp.MustCompile(pattern)

	// 判断在 b（s、r）中能否找到 pattern 所匹配的字符串
	if !regexpattern.MatchString(Telephone) {
		return errors.New(1, "手机号不合适", "")
	}
	return nil
}
func GetVerifycode(ctx context.Context, addr string) (string, error) {
	consulConfig := api.DefaultConfig()
	consulConfig.Address = "localhost:8500"
	consulClient, err := api.NewClient(consulConfig)
	if err != nil {
		log.Info(err)
	}
	dis := consul.New(consulClient)
	endpoint := "discovery:///verifyCode"

	conn, err := grpc.DialInsecure(ctx,
		grpc.WithEndpoint(endpoint),
		//verifycode grpc service地址
		//使用服务发现
		grpc.WithDiscovery(dis),
	)
	if err != nil {
		return "", err
	}
	defer func() {
		_ = conn.Close()
	}()
	client := verifyCode.NewVerifyCodeClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	reply, err := client.GetVerifyCode(ctx, &verifyCode.GetVerifyCodeRequest{
		Length: 6,
		Type:   1,
	})
	if err != nil {
		return "", nil
	}
	return reply.Code, nil
}
